package com.ozo.easy.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ozo.easy.common.file.IFileService;
import com.ozo.easy.common.model.*;
import com.ozo.easy.common.util.SortUtil;
import com.ozo.easy.common.exception.ServiceException;
import com.ozo.easy.exception.ServiceExceptionEnum;
import com.ozo.easy.entity.SysFile;
import com.ozo.easy.mapper.SysFileMapper;
import com.ozo.easy.pojo.dto.SysFileQueryDTO;
import com.ozo.easy.pojo.vo.SysFileVO;
import com.ozo.easy.service.ISysFileService;
import lombok.RequiredArgsConstructor;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.util.List;
import java.util.Objects;

/**
 * 文件 服务实现类
 *
 * @author ozo
 * @version 1.0
 * @date 2025-02-05 15:44:53
 */
@RequiredArgsConstructor
@Service
public class SysFileServiceImpl extends ServiceImpl<SysFileMapper, SysFile> implements ISysFileService {

    private final IFileService fileService;

    @Override
    public Long upload(MultipartFile file, String directory) {
        String relativePath = fileService.uploadFile(file, directory);

        SysFile sysFile = new SysFile();
        sysFile.setOriginalName(file.getOriginalFilename());
        sysFile.setFileName(relativePath.substring(relativePath.lastIndexOf(File.separator) + 1));
        sysFile.setFileSize((int) file.getSize());
        sysFile.setFileSuffix(file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf(".")));
        sysFile.setFilePath(relativePath);
        baseMapper.insert(sysFile);
        return sysFile.getId();
    }

    @Override
    public void download(Long id, HttpServletResponse response) {
        SysFile sysFile = baseMapper.selectById(id);
        if (Objects.isNull(sysFile)) {
            throw new ServiceException(ServiceExceptionEnum.DATA_NOT_EXISTS);
        }
        response.setHeader(HttpHeaders.CONTENT_DISPOSITION, "attachment;filename=" + sysFile.getFileName());
        response.setHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_OCTET_STREAM_VALUE);
        response.setHeader(HttpHeaders.CONTENT_LENGTH, String.valueOf(sysFile.getFileSize()));

        byte[] bytes = fileService.downloadFile(sysFile.getFilePath());
        try {
            response.getOutputStream().write(bytes);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void remove(BaseBatchDTO<Long> batchDTO) {
        baseMapper.deleteBatchIds(batchDTO.getIdList());
    }

    @Override
    public PageResult<SysFileVO> page(BasePage basePage, SysFileQueryDTO queryDTO) {
        Integer pageNum = basePage.getPageNum();
        Integer pageSize = basePage.getPageSize();

        QueryWrapper<SysFile> queryWrapper = new QueryWrapper<>();
        // 排序
        String order = queryDTO.getOrder();
        if (StrUtil.isBlank(order)) {
            queryWrapper.lambda().orderByDesc(SysFile::getId);
        } else {
            SortUtil.setSortCondition(queryWrapper, queryDTO.getProp(), order);
        }
        // 条件
        queryWrapper.lambda()
                .like(StrUtil.isNotBlank(queryDTO.getOriginalName()), SysFile::getOriginalName, queryDTO.getOriginalName());
        Page<SysFile> page = baseMapper.selectPage(new Page<>(pageNum, pageSize), queryWrapper);

        PageResult<SysFileVO> pageResult = new PageResult<>();
        pageResult.setPageNum(pageNum);
        pageResult.setPageSize(pageSize);
        pageResult.setPage(page.getPages());
        pageResult.setTotal(page.getTotal());
        List<SysFile> recordList = page.getRecords();

        List<SysFileVO> recordVOList = BeanUtil.copyToList(recordList, SysFileVO.class);

        pageResult.setResults(recordVOList);
        return pageResult;
    }

}
